import WeCropper from '../we-cropper/we-cropper.js'

// const WATERMARK_FONT = '@明曦小栈'
const app = getApp()
const config = app.globalData.config
const device = wx.getSystemInfoSync()

Page({
  data: {
    cropperOpt: {
      id: 'cropper',
      targetId: 'targetCropper',
      pixelRatio: device.pixelRatio,
      width: device.windowWidth,
      height: device.windowWidth,
      scale: 2.5,
      zoom: 8
    },
    themeConfig: config.theme
  },
  touchStart(e) {
    this.cropper.touchStart(e)
  },
  touchMove(e) {
    this.cropper.touchMove(e)
  },
  touchEnd(e) {
    this.cropper.touchEnd(e)
  },
  themeClickHandler(e) {
    const { name } = e.target.dataset
    config.theme.active = name
    this.setData({ themeConfig: config.theme })
    const { color } = this.data.themeConfig.items.find(item => item.name === name)
    config.setThemeColor(color)
  },
  getCropperImage() {
    this.cropper.getCropperImage(function (path, err) {
      if (err) {
        wx.showModal({
          title: '温馨提示',
          content: err.message
        })
      } else {
        wx.previewImage({
          current: path, // 当前显示图片的http链接
          urls: ['https://gldata.obs.cn-north-4.myhuaweicloud.com/yt.jpg'] // 需要预览的图片http链接列表
        })
      }
    })
  },
  uploadTap() {
    const self = this
    wx.chooseImage({
      count: 1, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success(res) {
        wx.showLoading({
          title: '替换背景中',
        })
        const src = wx.getFileSystemManager().readFileSync(res.tempFilePaths[0], 'base64')
        let activeColor=config.getThemeColor()
        wx.request({
          url: 'https://api.remove.bg/v1.0/removebg',
          method: 'post',
          data: {
            // image_url: 'https://gldata.obs.cn-north-4.myhuaweicloud.com/yt.jpg',
            image_file_b64: src,
            size: 'auto',
            bg_color: activeColor
          },
          responseType: 'arraybuffer',//响应方式
          timeout: 100000,
          header: {
            'content-type': 'application/x-www-form-urlencoded',
            'X-Api-Key': 'zkFgLK7J9FCZ1C67equkNhKK'
          },
          success(res) {
            let fileManager = wx.getFileSystemManager();//获取文件管理器
            let filePath = wx.env.USER_DATA_PATH + '/inner.jpg';//设置临时路径
            fileManager.writeFile({//获取到的数据写入临时路径
              filePath: filePath,//临时路径
              encoding: 'binary',//编码方式，二进制
              data: res.data,//请求到的数据
              success: function (res) {
                wx.previewImage({//图片预览
                  urls: [filePath],
                })
                wx.hideLoading();
              },
              fail: function (res) {
                wx.hideLoading();
              },
            });
          },
          fail(res) {
            console.log(res.data)
          }
        })
        // self.cropper.pushOrign(src)
      }
    })
  },
  onLoad(option) {
    const { cropperOpt } = this.data

    this.cropper = new WeCropper(cropperOpt)
      .on('ready', (ctx) => {
        console.log(`wecropper is ready for work!`)
      })
      .on('beforeImageLoad', (ctx) => {
        console.log(`before picture loaded, i can do something`)
        console.log(`current canvas context:`, ctx)
        wx.showToast({
          title: '上传中',
          icon: 'loading',
          duration: 20000
        })
      })
      .on('imageLoad', (ctx) => {
        console.log(`picture loaded`)
        console.log(`current canvas context:`, ctx)
        wx.hideToast()
      })
    // .on('beforeDraw', (ctx) => {
    //   console.log(`before canvas draw,i can do something`)
    //   console.log(`current canvas context:`, ctx)
    //   //  那就尝试在图片上加个水印吧
    //   // ctx.drawImage(path, 50, 50, 50, 30)
    //   ctx.setFontSize(14)
    //   ctx.setFillStyle('#ffffff')
    //   ctx.fillText(WATERMARK_FONT, 265, 350)
    //   console.log('123123123123123')
    // })
  }
})
